var defaultSoundLevel = 70;
var SNT_DEBUG = true;

/** 
 * @function
 * @description Init Sonettic-Cinema HD Player with SWFObject library. Flash object will be with transparent background. 
 * @param holder name of the DOM element which have to receive flash object
 * @param size Object with size of the player area ({ width : 100, height: 100 })
 * @param flashvars an array with list of players init flashvars
 * @param callback Callback function witch will be called after initialization of the flash object
 */
function SntInitWithSwfobject(holder, size, flashvars, callback){  
	var params = {  
	    'allowFullScreen' : 'true', 
	    'allowScriptAccess' : 'sameDomain',  
	    'bgcolor' : 'transparent',
	    'wmode' : 'transparent'
	};  
	  
	var attributes = {  
	    'id': holder,  
	    'name' : holder
	};  

	swfobject.addLoadEvent(callback);
	
	swfobject.embedSWF(  
	        "cinemaplayerdev.swf",   
	        holder,   
	        size.width,   
	        size.height,   
	        "9.0.0",  
	        "scripts/expressInstall.swf",   
	        flashvars,
	        params,
	        attributes
	);	
}

/**
 * @function
 * @desc This is callback method which called when Flash initalized by swfobject. Method initalize all 
 * 			events listeners and handlers
 * @param {String} obj Id of the holder object
 */
function initMellowblueSkin(obj){
	var skinObj = $('#' + obj);
	var videoHolderName = obj + 'videoholder';
	
	skinObj.find('.mellowblueVideoObject').attr('id', videoHolderName);

	var player = new SntPlayer(videoHolderName);
	
	function initSonetticCinemaJSAPI(){
		// get all controls by class name
		var playPauseButton = skinObj.find('.mellowblue-control-playback');
		var stopButton = skinObj.find('.mellowblue-control-playback-stop');
		var soundSlider = skinObj.find('.mellowblue-control-playback-volume');
		var soundLevel = skinObj.find('.mellowblue-volume-slider');
		var timelineHolder = skinObj.find('.mlb-timeline-slider');
		var timelineSlider = skinObj.find('.mlb-timeline-slider');
		var durationText = skinObj.find('.mellowblue-tml-len');
		var positionText = skinObj.find('.mellowblue-tml-pos');
		var timelineBuffering = skinObj.find('.mlb-buffering-slider');
		
		player.ready(function(r){			
			// play and pause
			var onPauseEvent = function(e){
				// change pause button to play
				playPauseButton.removeClass('mellowblue-pause');
				playPauseButton.addClass('mellowblue-play');	
				playPauseButton.unbind("click").click(playEvent);			
			};
			var onPlayEvent = function(){
				// enable stop button
				stopButton.removeClass('mellowblue-stop-disabled');
				stopButton.addClass('mellowblue-stop');
				
				// change apperance of the play button
				playPauseButton.addClass('mellowblue-pause');
				playPauseButton.removeClass('mellowblue-play');
				playPauseButton.unbind("click").click(pauseEvent);				
			};
			
			var onStopEvent = function(){
				// disable stop button
				stopButton.addClass('mellowblue-stop-disabled');
				stopButton.removeClass('mellowblue-stop');
				
				// enable play button
				onPauseEvent();	
			};
			
			// pause event function			
			var pauseEvent = function(){
				player.sendMessage('uiPauseClick');				
			};
						
			// play event
			var playEvent = function(){
				player.sendMessage('uiPlayClick');
			};
			
			// stop event
			var stopEvent = function(){ player.sendMessage('uiStopClick');	};
			
			// add events to dispatcher
			player.addEventListener('mediaPlay', onPlayEvent);
			player.addEventListener(['mediaPause'], onPauseEvent);
			player.addEventListener([ 'mediaStop', 'loadingStop' ], onStopEvent);
			
			// add handler for jQuery event `click`
			playPauseButton.click(playEvent);			
			// end of play and pause
			
			
			// stop downloading of the movie button (not pause)
			stopButton.click(stopEvent);



			// sound manipulations
			var soundLevelMax = soundLevel.width();
			// change volume function. It should change volume level by slider backgorund position
			var changeVolume = function(){
				var slCoef = 100 / soundLevelMax;
				// fix jquery backgroundPosition bug for IE
				if($.browser.msie){
					cssOffset =  soundLevel.css('backgroundPositionX') + ' ' +  soundLevel.css('backgroundPositionY');
					 soundLevel.css('backgroundPosition', cssOffset);
				}
				
				var currentSoundLevelArr = soundLevel.css('backgroundPosition').split(' ');
				if(currentSoundLevelArr.length != 2)return;
				var currentSoundLevel = 100 - Math.round(currentSoundLevelArr[0].replace('px', '') * -1 * slCoef);				
				player.sendMessage('soundValueSet', [currentSoundLevel]);				
			}
			
			// set default css offset by original sound level
			var setDefaultSoundValue = function(level){
				var slCoef = 100 / soundLevelMax;				
				var cssLevel = soundLevelMax - Math.round(level / slCoef);
				soundLevel.css('backgroundPosition', (-1 * cssLevel) + 'px 0');
				changeVolume();
			}
			// function to handle change volume events
			var onSoundChange = function(e){
				var xclick = e.clientX;
				var pos = soundLevel.offset();
				var changedVolume = xclick - pos.left;
				soundLevel.css('backgroundPosition', (-1 * (soundLevelMax - changedVolume)) + 'px 0');
				changeVolume();
			};
			
			// dispatch sound events
			soundSlider.click(onSoundChange);			
			setDefaultSoundValue(defaultSoundLevel);
			// end of sound level manipulations
			
			
			var tLen = timelineHolder.width();
			// change position of the timeline
			var changeTimelineSliderPosition = function(pos){
				var timelineOriginalLen = 1000;
				
				var timelineCssOffset = timelineSlider.css('backgroundPosition');
				
				// fix jquery backgroundPosition bug for IE
				if($.browser.msie){
					timelineCssOffset = timelineSlider.css('backgroundPositionX') + ' ' + timelineSlider.css('backgroundPositionY');
					timelineSlider.css('backgroundPosition', timelineCssOffset);
				}
				var realPosition = (timelineOriginalLen - pos) * -1;			
				timelineSlider.animate({
					'backgroundPosition' : '(' + realPosition + 'px ' + timelineCssOffset.split(' ')[1] + ')'
				}, 50);
				
			};
			
			// show buffering state
			var changeTimelineSliderBuffering = function(realSize, size, loaded){
				// skip changing of buffering apperance if size == 0
				if(size == 0 && loaded == 0)return;
				
				Sonettic.Helper.debug('Real size: ' + realSize + ', size: ' + size + ', loaded: ' + loaded);
				
				// for HTTP Stream
				if(size != realSize){
					loaded = loaded + (realSize - size);
				}
				
				var timelineOriginalLen = 1000;
				var coef = tLen / realSize;
				var tPos = Math.ceil(coef * loaded);
				
				var timelineCssOffset = timelineBuffering.css('backgroundPosition');
				// fix jquery backgroundPosition bug for IE
				if($.browser.msie){
					timelineCssOffset = timelineBuffering.css('backgroundPositionX') + ' ' + timelineBuffering.css('backgroundPositionY');
					timelineBuffering.css('backgroundPosition', timelineCssOffset);
				}
				
				var realPosition = (timelineOriginalLen - tPos) * -1;
				
				Sonettic.Helper.debug('Buffering slider BG Pos: ' + timelineCssOffset);
				
				timelineBuffering.animate({
					'backgroundPosition' : '(' + realPosition + 'px ' + timelineCssOffset.split(' ')[1] + ')'
				}, 50);				
			};
			
			// return formatted time
			var formatTime = function(seconds){
				var s = seconds;
				var m = 0;
				if(seconds > 60){
					m = Math.floor(seconds / 60)
					s = seconds % 60;
				}
				return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
			};
						
			// on media stop event change timeline position to 0 and
			// enable play button
			var onMediaStopStartPosition = function(){
				
				changeTimelineSliderPosition(0);
				onPauseEvent();
				positionText.text(formatTime(0));		
				
			};
			
			// state change
			var duration = 0.1;
			var onStateChange = function(s){
				duration = Math.ceil(s.duration);
				
				if(isNaN(duration))duration = 1;
				
				var position = Math.ceil(s.position);
				var coef = tLen / duration;
				var tPos = Math.ceil(coef * position);
				
				durationText.text(formatTime(duration));
				positionText.text(formatTime(position));
				
				changeTimelineSliderBuffering(s.realbytestotal, s.bytestotal, s.bytesloaded);				
				changeTimelineSliderPosition(tPos);
			};
			

			// add events to dispatcher
			player.addEventListener('mediaStopStartPosition', onMediaStopStartPosition);
			player.addEventListener('mediaStateChange', onStateChange);
			
			timelineHolder.click(function(e){
				var coef = tLen / duration;
				var posX = e.clientX;
				var offset = Math.ceil(posX - timelineHolder.offset().left);
				var position = Math.ceil(offset / coef);
				player.sendMessage('mediaSeek', [ position ]);
			});
			
		});	
	};
	
	//init skind with SWFObject and add callback to initalize Sonettic Cinema JS API object
	SntInitWithSwfobject(videoHolderName, {'width' : 470, 'height' : 264}, {
		'content' : '[filename]?start=[seek],http://www.sonettic.com.ua/cinema/video/flv/Walle1.flv',
		'zholdercornerradius' : 0,
		'zholderpadding' : 5,
		'slavemode' : true,
	    'playerID' : videoHolderName
	}, initSonetticCinemaJSAPI);
}



$(document).ready(function(){
	initMellowblueSkin('player1');
});